//
//  MBDUploadGroupQRCodeCell.swift
//  MasterBoy
//
//  Created by kyson on 2023/11/21.
//

import Foundation


import SnapKit
import YYText



class MBDUploadGroupQRCodeCell: MBDCommonCell {

    var codeImageView : UIImageView!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.initialize()
    }
    
    func initialize() {
        self.contentView.setDynamicForgroundColor()
        self.commonBackgroundView.setDynamicForgroundColor()

        codeImageView = UIImageView()
        self.contentView.addSubview(codeImageView)
        codeImageView.layer.cornerRadius = 4
        codeImageView.clipsToBounds = true
        codeImageView.image = UIImage(named: "ico_upload_add")
        
        codeImageView.snp.makeConstraints { make in
            make.centerY.equalTo(self.contentView)
            make.left.equalTo(30)
            make.size.equalTo(CGSizeMake(44, 44))
        }
    }
    
    override var cellModel: Any! {
        didSet {
            let realCellModel = cellModel as! MBDUploadGroupQRCodeCellModel
            let imageURLString = realCellModel.qrCodePath ?? ""
            let praisedQRCode = realCellModel.praisedQRCode ?? ""
            
            if imageURLString.isBlank == false {
                
                if imageURLString.hasPrefix(MBDPath2URLUtils.filePathPrefix) {
                    let imageName = imageURLString.replacingOccurrences(of: MBDPath2URLUtils.filePathPrefix, with: "")
                    self.codeImageView.image = UIImage(named: imageName)
                } else {
                    let urlString = MBDPath2URLUtils.wrapGroupLogoURL(path: imageURLString)
                    let url = URL.init(string: urlString)
                    self.codeImageView.kf.setImage(with: url)
                }
                
            } else if praisedQRCode.isBlank == false {
                let urlString = MBDPath2URLUtils.wrapGroupLogoURL(path: praisedQRCode)
                let url = URL.init(string: urlString)
                //异步加载
                DispatchQueue.global().async {
                    
                    let qrCode = QRCodeUtils.qrcodeWithUrl(groupUrl: urlString)
                    DispatchQueue.main.async {
                        self.codeImageView.image = qrCode
                    }
                }
                

            } else {
                self.codeImageView.image = UIImage(named: "ico_upload_add")
            }
            self.accessable = false
        }
    }

}
